<template>
  <div v-loading="loading" class="main">
    <xr-header
      label="新建打印模板">
      <template slot="ft">
        <el-button
          type="text"
          @click="perviewClick">预览</el-button>
        <el-button
          v-debounce="saveClick"
          type="primary">保存</el-button>
        <el-button
          @click="goBackClick">返回</el-button>
      </template>
    </xr-header>
    <div class="main-body">
      <!-- 客户管理导航 -->
      <div class="system-view-nav">
        <el-tabs v-model="activeTab" @tab-click="tabsClick">
          <el-tab-pane
            v-for="(item, index) in tabs"
            :key="index"
            :label="item.label"
            :name="item.key" />
        </el-tabs>
        <reminder
          content="点击字段插入值（光标所在位置）"
          class="xr-reminder" />
        <div class="menus">
          <div
            v-for="(item, index) in menuList"
            :key="index"
            :class="{'is-select' : item.fieldName == menuIndex}"
            class="menu-item  text-one-line"
            @click="menuSelect(item, index)">
            {{ item.name }}
          </div>
        </div>
      </div>
      <div class="system-view-content">
        <tinymce
          ref="createTinymce"
          v-model="content"
          :toolbar="toolbar"
          :plugins="plugins"
          :height="richHeight"
          :init="getEditConfig()"
          is-print
          class="rich-txt" />
      </div>
    </div>
  </div>
</template>

<script>
import {
  oaExaminePrintTemplateFieldsAPI,
  oaExaminePrintTemplateAddAPI,
  oaExaminePrintTemplateUpdateAPI,
  oaExaminePrintTemplateQueryByIdAPI
} from '@/api/admin/oa'

import XrHeader from '@/components/XrHeader'
import Reminder from '@/components/Reminder'
import Tinymce from '@/components/Tinymce'

import Toolbar from '@/components/Tinymce/toolbar'
import Plugins from '@/components/Tinymce/plugins'

export default {
  name: 'PrintTemplateDetail',

  components: {
    XrHeader,
    Reminder,
    Tinymce
  },

  data() {
    return {
      loading: false,
      activeTab: '',
      tabs: [],
      tabData: {},
      menuIndex: '',
      richHeight: document.documentElement.clientHeight - 130,
      content: '',

      // 控制选择的内容
      selectNodes: null,
      toolbar: `${Toolbar} | watermark | signature signature-top signature-bottom signature-left signature-right`,
      plugins: `${Plugins} watermark signature`
    }
  },

  computed: {
    menuList() {
      // 没有字段名的不展示
      return (this.tabData[this.activeTab] || []).filter(o => !!o.name)
    },

    // 审批Id
    configId() {
      return this.$route.query.configId
    },

    isCreate() {
      return this.$route.query.handle == 'create'
    },

    editor() {
      return this.$refs.createTinymce.editor
    }
  },

  created() {
    this.getFields(this.configId)
    if (!this.isCreate) {
      this.getDetail()
    }
  },

  methods: {
    /** *
     * 获取详情
     */
    getDetail() {
      this.loading = true
      oaExaminePrintTemplateQueryByIdAPI({
        templateId: this.$route.query.templateId
      }).then(res => {
        const data = res.data || {}
        this.content = data.content

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     *获取字段数据
     */
    getFields(configId) {
      this.loading = true
      oaExaminePrintTemplateFieldsAPI({
        templateId: configId
      }).then(res => {
        const data = res.data || {}
        this.tabData = data

        const tabs = []
        const defaultSort = ['examineFields', 'travelFields', 'recordFields']
        defaultSort.forEach(key => {
          const dataList = data[key]
          if (key === 'examineFields') {
            // 记录一下父明细表格字段
            const detailTableObj = {}

            dataList.forEach(o => {
              // 记录一下父明细表格字段
              if (o.formType === 'detail_table') {
                detailTableObj[o.fieldId] = o
              }

              // 包含明细表格字段id的父字段
              if (o.parentFieldId) {
                const detailTableItem = detailTableObj[o.parentFieldId]
                if (detailTableItem) {
                  o.name = `${detailTableItem.name}-${o.name}`
                }
              }
            })
          }
          if (dataList && dataList.length > 0) {
            const temp = { key }
            temp.label = {
              examineFields: '审批字段',
              travelFields: {
                3: '行程明细',
                5: '费用明细'
              }[data.oaType],
              recordFields: '审批记录明细'
            }[key]
            tabs.push(temp)
          }
        })
        this.tabs = tabs
        if (tabs.length > 0) {
          this.activeTab = tabs[0].key
        } else {
          this.activeTab = ''
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 左侧操作 */
    tabsClick() {
      this.menuIndex = ''
    },

    menuSelect(item, index) {
      // console.log(this.editor.selection.getNode())
      this.menuIndex = item.fieldName
      const currentTab = this.tabs.find(item => item.key === this.activeTab)
      const tableParent = this.getCurrentParentByTag('table[data-wk-table-tag="table"]')
      if (['travelFields', 'recordFields'].includes(currentTab.key)) {
        if (tableParent && tableParent.dataset.wkTableValue === currentTab.key) {
          const headerTr = this.editor.dom.select('tr[data-wk-table-tr-tag="header"]', tableParent)
          const valueTr = this.editor.dom.select('tr[data-wk-table-tr-tag="value"]', tableParent)
          if (headerTr && valueTr) {
            this.editor.dom.add(headerTr, 'td', { 'data-wk-table-td-tag': 'name' }, item.name)
            this.editor.dom.add(valueTr, 'td', { 'data-wk-table-td-tag': 'value' }, this.getSpanNode(item, 'table-value'))
            this.content = this.editor.getContent({ format: 'html' })
          }
        } else {
          if (!this.getCurrentParentByTag('table')) {
            this.editor.insertContent(this.getProuctTable([item], currentTab.key))
          }
        }
      } else if (item.formType === 'detail_table' || item.parentFieldId) {
        let children = []
        let tableValue = ''
        if (item.formType === 'detail_table') {
          children = this.menuList.filter(o => o.parentFieldId === item.fieldId)
          tableValue = item.fieldId
        } else {
          children.push(item)
          tableValue = item.parentFieldId
        }

        if (!tableParent) {
          this.editor.insertContent(this.getProuctTable(children, tableValue))
        } else {
          if (tableParent.dataset.wkTableValue !== tableValue) {
            // 如果相同不允许修改
            return
          }
          const headerTr = this.editor.dom.select('tr[data-wk-table-tr-tag="header"]', tableParent)
          const valueTr = this.editor.dom.select('tr[data-wk-table-tr-tag="value"]', tableParent)
          if (headerTr && valueTr) {
            children.forEach(o => {
              this.editor.dom.add(headerTr, 'td', { 'data-wk-table-td-tag': 'name' }, o.name)
              this.editor.dom.add(valueTr, 'td', { 'data-wk-table-td-tag': 'value' }, this.getSpanNode(o, 'table-value'))
            })
          }
          this.content = this.editor.getContent({ format: 'html' })
        }
      } else {
        const tableParent = this.getCurrentParentByTag('table[data-wk-table-tag="table"]')
        if (!tableParent) {
          this.editor.insertContent(this.getSpanNode(item))
          this.content = this.editor.getContent({ format: 'html' })
        }
      }
    },

    /**
     * 根据选择器获取父元素
     */
    getCurrentParentByTag(tag) {
      return this.editor.dom.getParent(this.editor.selection.getNode(), tag)
    },

    /**
     * 获取产品表
     * tableValue table字段的filedId
     */
    getProuctTable(list, tableValue) {
      let nameTds = ''
      let valueTds = ''
      list.forEach(item => {
        nameTds += `<td data-wk-table-td-tag="name">${item.name}</td>`
        valueTds += `<td data-wk-table-td-tag="value">${this.getSpanNode(item, 'table-value')}</td>`
      })

      return `<table data-wk-table-tag="table" data-wk-table-value="${tableValue}" style="border-collapse: collapse; width: 100%;" border="1" >
      <tbody>
      <tr data-wk-table-tr-tag="header">${nameTds}</tr>
      <tr data-wk-table-tr-tag="value">${valueTds}</tr>
      </tbody>
      </table>`
    },

    /**
     * 获取基础span属性
     */
    getSpanNodeAttrs(item, tag = '') {
      return this.getSpanNodeAttrsByType(item, tag, this.activeTab)
    },

    getSpanNodeAttrsByType(item, tag = '', type) {
      const attrs = {}
      const dataKey = `data-wk${tag ? `-${tag}` : ''}-tag`
      const dataValue = item.parentFieldId ? `${item.parentFieldId}.${item.fieldId}` : `${type}.${item.fieldName}`

      attrs[dataKey] = dataValue
      attrs.class = `wk-print-tag-wukong ${this.getSpanColorClass()}`
      attrs.contenteditable = false
      return attrs
    },

    getSpanNode(item, tag = '', type = this.activeTab) {
      const dataValue = item.parentFieldId ? `${item.parentFieldId}.${item.fieldId}` : `${type}.${item.fieldName}`
      return `<span data-wk${tag ? `-${tag}` : ''}-tag="${dataValue}" class="wk-print-tag-wukong ${this.getSpanColorClass()}" contenteditable="false">{${item.name}}</span>`
    },

    /**
     * span 颜色
     */
    getSpanColorClass() {
      // const color = ['customer', 'contacts', 'business', 'contract', 'receivables', 'product'].includes(this.activeTab) ? this.activeTab : 'common'
      // return `wk-tiny-color--${color}`
      return 'wk-tiny-color--common'
    },

    /** 顶部操作 */

    /**
     * 预览
     */
    perviewClick() {
      this.editor.execCommand('mcePreview')
    },

    /**
     * 保存
     */
    saveClick() {
      this.loading = true
      const request = this.isCreate ? oaExaminePrintTemplateAddAPI : oaExaminePrintTemplateUpdateAPI
      const data = this.$route.query
      const params = {
        templateName: data.templateName,
        configId: data.configId,
        content: this.content
      }

      if (!this.isCreate) {
        params.templateId = data.templateId
      }

      request(params)
        .then(res => {
          this.loading = false
          if (this.isCreate) {
            this.$message({
              type: 'success',
              message: '新建成功'
            })
            this.$router.go(-1)
          } else {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 保存
     */
    goBackClick() {
      this.$router.go(-1)
    },

    /** 富文本配置 */
    getEditConfig() {
      return {
        menubar: false,
        toolbar_sticky: true,
        statusbar: false,
        // extended_valid_elements: 'span[class|title|wktag|style|contenteditable]',
        content_style: 'p { margin: 5px 0; line-height: 1.5;}',
        content_css: ['./static/tinymce/css/tiny-wk-colors.css', './static/tinymce/css/tiny-wk-word.css'],
        table_advtab: false,
        table_cell_advtab: false,
        table_row_advtab: false,
        setup: (editor) => {
          editor.on('init', function(e) {
            editor.execCommand('mceFocus')
          })
          editor.on('keydown', (e) => {
            this.selectNodes = null
            if (e.keyCode === 8 /* Backspace key */ || /* del key */ e.keyCode == 46) {
              const currentNode = editor.selection.getNode()
              if (currentNode.getAttribute('data-wk-table-td-tag') === 'value') {
                e.preventDefault()
                return false
              } else if (currentNode.nodeName == 'SPAN') {
                if (currentNode.hasAttribute('contenteditable')) {
                  e.preventDefault()
                  editor.dom.remove(currentNode)
                  return false
                } else {
                  const farterSpan = this.getCurrentParentByTag('span[contenteditable]')
                  if (farterSpan) {
                    e.preventDefault()
                    editor.dom.remove(farterSpan)
                    return false
                  }
                }
              }
            } else if (e.keyCode == '65' && (e.metaKey || e.ctrlKey)) { // 全选
              this.selectNodes = editor.selection.getNode()
              this.setSpanEditAttr(this.selectNodes, true)
            } else {
              // table 里面不允许写内容
              const currentNode = editor.selection.getNode()
              if (currentNode.getAttribute('data-wk-table-td-tag') === 'value') {
              // 只允许输入上下左右
                if (e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40) {
                  e.preventDefault()
                  return false
                }
              } else if (currentNode.nodeName == 'SPAN') {
                if (currentNode.hasAttribute('contenteditable')) {
                  if (currentNode.getAttribute('contenteditable')) {
                    e.preventDefault()
                    currentNode.setAttribute('contenteditable', false)
                    return false
                  }
                  return false
                } else {
                  const farterSpan = this.getCurrentParentByTag('span[contenteditable]')
                  if (farterSpan) {
                    if (farterSpan.getAttribute('contenteditable')) {
                      e.preventDefault()
                      farterSpan.setAttribute('contenteditable', false)
                      return false
                    }
                    return false
                  }
                }
              }

              if (e.keyCode == 37 && e.keyCode == 38 && e.keyCode == 39 && e.keyCode == 40) {
                // console.log('上下左右')
                this.cancelSpanEdit()
              }
            }
          })

          // editor.on('focusin', function(e) {
          //   console.log('focusin')
          // })

          // editor.on('focusout', function(e) {
          //   console.log('focusout')
          // })

          // editor.on('click', function(e) {
          //   console.log('click')
          // })

          // editor.on('blur', (e) => {
          //   console.log('blur')
          // })

          editor.on('mousedown', (e) => {
            this.cancelSpanEdit()
          })

          editor.on('mouseup', (e) => {
            const selection = editor.selection.getSel()
            // console.log(selection.isCollapsed, selection.anchorNode == selection.focusNode, selection.anchorOffset == selection.focusOffset)

            if (e.target.hasAttribute('contenteditable') && selection.anchorOffset == 1 && selection.anchorOffset == 1) {
              // 忽略
            } else if (e.target.hasAttribute('contenteditable') && selection.isCollapsed) {
              this.cancelSpanEdit()
            } else {
              if (!selection.isCollapsed) {
                this.selectNodes = editor.selection.getNode()
                this.setSpanEditAttr(this.selectNodes, true)
              } else {
                this.cancelSpanEdit()
              }
            }
          })
        }
      }
    },

    /**
     * 取消编辑
     */
    cancelSpanEdit() {
      if (this.selectNodes) {
        setTimeout(() => {
          const selection = this.editor.selection.getSel()
          if (!selection.isCollapsed) {
            this.setSpanEditAttr(this.selectNodes, false)
            this.selectNodes = null
          }
        }, 300)
      }
    },

    /**
     * 操控span是否可编辑
     */
    setSpanEditAttr(node, canEdit) {
      if (node && node.hasAttribute('contenteditable')) {
        if (node.getAttribute('contenteditable') != canEdit) {
          node.setAttribute('contenteditable', canEdit)
        }
      }

      if (node && node.children) {
        for (let index = 0; index < node.children.length; index++) {
          const element = node.children[index]
          if (element.children) {
            this.setSpanEditAttr(element, canEdit)
          } else if (element.hasAttribute('contenteditable')) {
            if (node.getAttribute('contenteditable') != canEdit) {
              element.setAttribute('contenteditable', canEdit)
            }
          }
        }
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../styles/index.scss";

.main-body {
  display: flex;
  height: calc(100% - 45px);
  margin-top: #{$--interval-base * 2};
}

.system-view-nav {
  position: relative;
  width: 300px;
  padding-top: 10px;
  margin-right: 10px;
  background: #fff;
  border: 1px solid $--border-color-base;
  border-radius: $--border-radius-base;

  ::v-deep .el-tabs {
    padding: 0 5px;
    border-bottom: 1px solid #e4e7ed;

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__header {
      margin-bottom: 0;
    }
  }
}

.system-view-content {
  flex: 1;
  height: 100%;
  background: #fff;
  border: 1px solid $--border-color-base;
  border-radius: $--border-radius-base;

  ::v-deep .tox-tinymce {
    border: none;
  }
}

// 菜单
.menus {
  height: calc(100% - 90px);
  overflow-y: auto;
}

.menu-item {
  position: relative;
  height: 40px;
  padding: 0 15px;
  font-size: 13px;
  line-height: 40px;
  color: $--color-text-primary;
  cursor: pointer;

  .icon-close {
    position: absolute;
    top: 0;
    right: 8px;
    z-index: 1;
    display: none;
  }
}

.menu-item:hover,
.menu-item.is-select {
  background-color: $--background-color-base;
}

.menu-item:hover::before,
.menu-item.is-select::before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 2px;
  content: " ";
  background-color: #5383ed;
}

.xr-reminder {
  ::v-deep .reminder-body {
    align-items: stretch;
    width: 100%;
    height: 35px;
    line-height: 35px;
    border-radius: 0;
  }
}
</style>
